package com.zk.algorithm.tree;

import com.zk.algorithm.bean.TreeNode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 求树的镜像
 *
 * @author zk
 */
public class InvertBinaryTree {

    // =================
    // DFS
    // =================

    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

        root.left = invertTree(root.right);
        root.right = invertTree(root.left);

        return root;
    }

    // =================
    // 迭代
    // =================

    public void invertTree4(TreeNode root) {
        if (root == null) {
            return;
        }

        if (root.left == null && root.right == null) {
            return;
        }

        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;

        if (root.left != null) {
            invertTree4(root.left);
        }

        if (root.right != null) {
            invertTree4(root.right);
        }
    }

    public TreeNode invertTree2(TreeNode root) {
        if (root == null) {
            return null;
        }

        final Deque<TreeNode> stack = new LinkedList<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            final TreeNode node = stack.pop();

            final TreeNode left = node.left;
            node.left = node.right;
            node.right = left;

            if (node.left != null) {
                stack.push(node.left);
            }

            if (node.right != null) {
                stack.push(node.right);
            }
        }
        return root;
    }

    public TreeNode invertTree3(TreeNode root) {
        if (root == null) {
            return null;
        }

        final Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            final TreeNode node = queue.poll();

            final TreeNode left = node.left;
            node.left = node.right;
            node.right = left;

            if (node.left != null) {
                queue.offer(node.left);
            }

            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return root;
    }

}
